<script setup>
import { ref, onMounted } from "vue";

// 提示文本状态变量
const infoTextType = ref("addPoint"); // 空字符串表示不显示提示

// 存储所有点位
const points = ref([]);
// 当前拖拽的点位索引
let draggingPointIndex = -1;
// 拖拽的偏移量
let offsetX = 0;
let offsetY = 0;
// 右键菜单状态
const contextMenu = ref({
  show: false,
  x: 0,
  y: 0,
  pointIndex: -1,
});

// 编辑名称弹窗状态
const editNameModal = ref({
  show: false,
  x: 0,
  y: 0,
  pointIndex: -1,
  name: "",
});

console.log("开始工具栏", "******************************************");

// 当前鼠标悬停的点位索引
let hoveredPointIndex = -1;

// 编辑模式状态
const isEditing = ref(true);
// 绘画模式状态
const isDrawing = ref(false);
// 当前是否正在绘制线条
let isDrawingLine = false;
// 存储自由绘制的线条
const freeDrawings = ref([]);
// 当前正在绘制的线条
let currentDrawing = [];
// 当前记录的点位坐标组
let currentPointCoordinates = [];
// 存储点位之间的绘画坐标组
const drawingCoordinateGroups = ref([]);
// 存储所有保存的线条坐标组
const savedDrawingCoordinateGroups = ref([]);
// 添加线条拖拽相关状态
let isDraggingLine = false;
let draggedLineIndex = -1;
let draggedLineOffsetX = 0;
let draggedLineOffsetY = 0;
// 线条选中状态
let selectedLineIndex = -1;
// 鼠标悬停线条状态
let hoveredLineIndex = -1;
// 图层相关状态
const savedLayers = ref([]); // 存储保存的图层数据
const showLines = ref(true); // 控制是否显示线条
const showSaveLayerButton = ref(false); // 是否显示保存图层按钮
// 新的轨迹展示功能相关状态
const layerPointIds = ref(""); // 输入图层点位ID的输入框
const showTrajectoryInput = ref(false); // 控制是否显示轨迹输入框和按钮
// 轨迹展示后禁止拖拽状态
const disableDragging = ref(false); // 控制展示轨迹后是否禁止拖拽
// 控制撤销按钮显示状态
const showUndoButton = ref(true); // 控制撤销按钮的显示
// 控制添加点位和开始连线按钮的显示
const showDrawingButtons = ref(true); // 控制添加点位和开始连线按钮的显示

// 添加点位
const addPoint = () => {
  // 设置提示文本类型
  infoTextType.value = "addPoint";

  // 生成100-999之间的随机三位数字作为id
  const generateThreeDigitId = () => {
    return Math.floor(Math.random() * 900) + 100;
  };

  const newPoint = {
    id: generateThreeDigitId(),
    x: 50, // 默认位置
    y: 50,
    width: 25,
    height: 25,
    color: getRandomColor(), // 随机颜色
    name: "", // 点位名称，默认为空
  };
  points.value.push(newPoint);
  // 重新绘制canvas
  drawCanvas();
};

// 生成随机颜色
const getRandomColor = () => {
  const colors = [
    "#FF6B6B",
    "#4ECDC4",
    "#45B7D1",
    "#96CEB4",
    "#FFEAA7",
    "#DDA0DD",
    "#98D8C8",
  ];
  return colors[Math.floor(Math.random() * colors.length)];
};

// 处理拖拽开始事件
const handleDragStart = (e) => {
  // 获取拖拽点位的背景颜色
  const bgColor = e.target.style.backgroundColor;
  // 将颜色存储在拖拽数据中
  e.dataTransfer.setData("text/plain", bgColor);
};

// 处理拖拽悬停事件
const handleDragOver = (e) => {
  // 阻止默认行为，允许放置
  e.preventDefault();
};

// 处理放置事件
const handleDrop = (e) => {
  e.preventDefault();

  // 如果是编辑模式且没有禁用拖拽
  if (isEditing.value && !disableDragging.value) {
    // 获取canvas元素
    const canvas = document.getElementById("myCanvas");
    const rect = canvas.getBoundingClientRect();
    // 计算相对于canvas的坐标
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    // 获取拖拽的颜色数据
    const color = e.dataTransfer.getData("text/plain");

    // 生成100-999之间的随机三位数字作为id
    const generateThreeDigitId = () => {
      return Math.floor(Math.random() * 900) + 100;
    };

    // 创建新点位
    const newPoint = {
      id: generateThreeDigitId(),
      x: x - 12.5, // 调整位置使中心点在鼠标位置
      y: y - 12.5,
      width: 25,
      height: 25,
      color: color || getRandomColor(), // 如果没有颜色数据则使用随机颜色
      name: "", // 点位名称，默认为空
    };

    // 添加新点位
    points.value.push(newPoint);
    // 重新绘制canvas
    drawCanvas();

    // 显示添加点位的提示信息
    infoTextType.value = "addPoint";

  }
};

// 绘制画布的核心函数
const drawCanvas = () => {
  // 获取canvas元素和绘图上下文
  const canvas = document.getElementById("myCanvas");
  const ctx = canvas.getContext("2d"); // 2D绘图上下文

  // 打印调试信息，显示当前线条数量
  console.log("进入drawCanvas - freeDrawings长度:", freeDrawings.value.length);

  // 清空整个画布，准备重新绘制
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 绘制辅助线（拖动点位时显示）
  if (draggingPointIndex !== -1) {
    const draggedPoint = points.value[draggingPointIndex];
    const draggedCenterX = draggedPoint.x + draggedPoint.width / 2;
    const draggedCenterY = draggedPoint.y + draggedPoint.height / 2;

    // 绘制水平辅助线
    ctx.beginPath();
    ctx.strokeStyle = "rgba(255, 140, 0, 0.3)";
    ctx.lineWidth = 1;
    ctx.setLineDash([5, 5]);
    ctx.moveTo(0, draggedCenterY);
    ctx.lineTo(canvas.width, draggedCenterY);
    ctx.stroke();
    ctx.closePath();

    // 绘制垂直辅助线
    ctx.beginPath();
    ctx.strokeStyle = "rgba(255, 140, 0, 0.3)";
    ctx.lineWidth = 1;
    ctx.setLineDash([5, 5]);
    ctx.moveTo(draggedCenterX, 0);
    ctx.lineTo(draggedCenterX, canvas.height);
    ctx.stroke();
    ctx.closePath();

    // 重置线条样式
    ctx.setLineDash([]);

    // 检查是否与其他点位在同一水平或垂直线上
    points.value.forEach((point, index) => {
      if (index !== draggingPointIndex) {
        const pointCenterX = point.x + point.width / 2;
        const pointCenterY = point.y + point.height / 2;

        // 同一水平线
        if (Math.abs(pointCenterY - draggedCenterY) < 2) {
          ctx.beginPath();
          ctx.strokeStyle = "rgba(255, 69, 0, 0.8)";
          ctx.lineWidth = 2;
          ctx.setLineDash([3, 2]);
          ctx.moveTo(0, draggedCenterY);
          ctx.lineTo(canvas.width, draggedCenterY);
          ctx.stroke();
          ctx.closePath();

          // 绘制交点指示
          ctx.beginPath();
          ctx.fillStyle = "rgba(255, 69, 0, 0.8)";
          ctx.arc(draggedCenterX, draggedCenterY, 5, 0, 2 * Math.PI);
          ctx.fill();
          ctx.closePath();
        }

        // 同一垂直线
        if (Math.abs(pointCenterX - draggedCenterX) < 2) {
          ctx.beginPath();
          ctx.strokeStyle = "rgba(255, 69, 0, 0.8)";
          ctx.lineWidth = 2;
          ctx.setLineDash([3, 2]);
          ctx.moveTo(draggedCenterX, 0);
          ctx.lineTo(draggedCenterX, canvas.height);
          ctx.stroke();
          ctx.closePath();

          // 绘制交点指示
          ctx.beginPath();
          ctx.fillStyle = "rgba(255, 69, 0, 0.8)";
          ctx.arc(draggedCenterX, draggedCenterY, 5, 0, 2 * Math.PI);
          ctx.fill();
          ctx.closePath();
        }
      }
    });
  }

  // 重置线条样式
  ctx.setLineDash([]);

  // 第二步：绘制所有自由绘制的线条（已保存的曲线）
  if (showLines.value && freeDrawings.value.length > 0) {
    freeDrawings.value.forEach((drawing, index) => {
      if (drawing.length > 0) {
        ctx.beginPath();

        // 检查当前线条是否被选中、正在被拖拽或鼠标悬停
        if (isDraggingLine && draggedLineIndex === index) {
          // 拖拽中的线条样式
          ctx.strokeStyle = "#FF6B6B"; // 使用红色
          ctx.lineWidth = 6; // 更粗的线宽
          ctx.setLineDash([5, 5]); // 虚线样式
        } else if (selectedLineIndex === index) {
          // 选中的线条样式
          ctx.strokeStyle = "#FFD700"; // 金色
          ctx.lineWidth = 6; // 更粗的线宽
          ctx.setLineDash([]); // 实线样式
        } else if (hoveredLineIndex === index) {
          // 鼠标悬停的线条样式
          ctx.strokeStyle = "#FF9800"; // 橙色
          ctx.lineWidth = 5; // 中等线宽
          ctx.setLineDash([]); // 实线样式
        } else {
          // 普通线条样式
          ctx.strokeStyle = "#0089FF"; // 默认蓝色
          ctx.lineWidth = 4; // 线条宽度
          ctx.setLineDash([]); // 实线样式
        }

        ctx.lineCap = "round"; // 线条两端为圆形
        ctx.lineJoin = "round"; // 线条连接处为圆形（使曲线更平滑）

        // 移动到线条的第一个点
        ctx.moveTo(drawing[0].x, drawing[0].y);

        // 判断线条的点数和类型，处理不同类型的连接
        if (drawing.length === 2 && drawing[0].isArc) {
          // 处理圆弧形连接
          const startX = drawing[0].x;
          const startY = drawing[0].y;
          const endX = drawing[1].x;
          const endY = drawing[1].y;
          const cornerRadius =
            drawing[1].radius ||
            Math.min(Math.abs(endX - startX), Math.abs(endY - startY)) * 0.4;

          // 根据起点和终点的相对位置确定圆弧方向
          if (startX < endX) {
            // 起点在终点左侧
            if (startY < endY) {
              // 起点在终点左下方
              ctx.lineTo(endX - cornerRadius, startY);
              ctx.arcTo(endX, startY, endX, endY, cornerRadius);
            } else {
              // 起点在终点左上方
              ctx.lineTo(endX - cornerRadius, startY);
              ctx.arcTo(endX, startY, endX, endY, cornerRadius);
            }
          } else {
            // 起点在终点右侧
            if (startY < endY) {
              // 起点在终点右下方
              ctx.lineTo(endX + cornerRadius, startY);
              ctx.arcTo(endX, startY, endX, endY, cornerRadius);
            } else {
              // 起点在终点右上方
              ctx.lineTo(endX + cornerRadius, startY);
              ctx.arcTo(endX, startY, endX, endY, cornerRadius);
            }
          }
          ctx.lineTo(endX, endY); // 连接到终点
        } else if (drawing.length === 4) {
          // 如果有4个点，使用三次贝塞尔曲线绘制
          ctx.bezierCurveTo(
            drawing[1].x,
            drawing[1].y, // 第一个控制点
            drawing[2].x,
            drawing[2].y, // 第二个控制点
            drawing[3].x,
            drawing[3].y // 终点
          );
        } else if (drawing.length === 3) {
          // 如果有3个点，使用二次贝塞尔曲线绘制
          ctx.quadraticCurveTo(
            drawing[1].x,
            drawing[1].y, // 控制点
            drawing[2].x,
            drawing[2].y // 终点
          );
        } else {
          // 其他情况，依次连接线条的其余点
          for (let i = 1; i < drawing.length; i++) {
            ctx.lineTo(drawing[i].x, drawing[i].y);
          }
        }

        ctx.stroke(); // 描边显示线条
        ctx.closePath(); // 关闭路径

        // 重置线条样式，避免影响后续绘制
        ctx.setLineDash([]);
      }
    });
  }

  // 第三步：绘制当前正在绘制的线条（用户正在画的线）
  if (showLines.value && isDrawingLine && currentDrawing.length > 0) {
    ctx.beginPath();
    ctx.strokeStyle = "#0089FF"; // 默认蓝色
    ctx.lineWidth = 4;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";

    // 移动到线条的第一个点
    ctx.moveTo(currentDrawing[0].x, currentDrawing[0].y);

    // 依次连接线条的其余点
    for (let i = 1; i < currentDrawing.length; i++) {
      ctx.lineTo(currentDrawing[i].x, currentDrawing[i].y);
    }

    ctx.stroke(); // 描边显示线条
    ctx.closePath(); // 关闭路径
  }

  // 第四步：绘制所有点位（最后绘制，确保点位显示在最上层）
  points.value.forEach((point) => {
    // 检查是否正在绘画且鼠标接近该点位（作为第二个点位）
    let isHighlighted = false;
    if (isDrawingLine && isDrawing.value && currentDrawing.length > 0) {
      const pointCenterX = point.x + point.width / 2;
      const pointCenterY = point.y + point.height / 2;
      const startPointX = currentDrawing[0].x;
      const startPointY = currentDrawing[0].y;
      const mouseX = currentDrawing[currentDrawing.length - 1].x;
      const mouseY = currentDrawing[currentDrawing.length - 1].y;

      // 计算鼠标与点位中心的距离
      const distance = Math.sqrt(
        Math.pow(mouseX - pointCenterX, 2) + Math.pow(mouseY - pointCenterY, 2)
      );

      // 如果距离小于阈值，且不是起点对应的点位，则高亮显示
      const isNotStartPoint = !(
        Math.abs(pointCenterX - startPointX) < 10 &&
        Math.abs(pointCenterY - startPointY) < 10
      );
      isHighlighted = distance < 25 && isNotStartPoint;
    }

    // 如果点位被高亮，绘制特殊样式
    if (isHighlighted) {
      // 绘制选中效果（发光边框）
      ctx.beginPath();
      ctx.strokeStyle = "#FFD700"; // 金色
      ctx.lineWidth = 4;
      ctx.strokeRect(
        point.x - 5,
        point.y - 5,
        point.width + 10,
        point.height + 10
      );
      ctx.closePath();

      // 绘制点位的填充颜色
      ctx.fillStyle = "#FFD700"; // 金色填充
      ctx.fillRect(point.x, point.y, point.width, point.height);
    } else {
      // 绘制点位的填充颜色
      ctx.fillStyle = point.color;
      ctx.fillRect(point.x, point.y, point.width, point.height);
    }

    // 绘制点位的黑色边框
    ctx.strokeStyle = "#333";
    ctx.lineWidth = 2;
    ctx.strokeRect(point.x, point.y, point.width, point.height);

    // 在点位中心显示点位ID（截取最后3位避免过长）
    ctx.fillStyle = "#fff"; // 白色文字
    ctx.font = "12px Arial"; // 字体和大小
    ctx.textAlign = "center"; // 文字居中对齐
    ctx.textBaseline = "middle"; // 文字垂直居中

    // 将ID转换为字符串，并截取最后几位显示（避免过长）
    const idStr = point.id.toString().slice(-3);
    // 计算点位中心点
    const centerX = point.x + point.width / 2;
    const centerY = point.y + point.height / 2;
    // 在中心点绘制点位ID
    ctx.fillText(idStr, centerX, centerY);

    // 如果鼠标悬停在该点位上且有点位名称，显示名称
    if (
      hoveredPointIndex !== -1 &&
      points.value[hoveredPointIndex].id === point.id &&
      point.name
    ) {
      // 绘制白色背景
      const nameWidth = ctx.measureText(point.name).width + 8;
      ctx.fillStyle = "#fff";
      ctx.fillRect(point.x - 5, point.y - 25, nameWidth, 20);
      // 绘制黑色文字
      ctx.fillStyle = "#000";
      ctx.font = "12px Arial";
      ctx.textAlign = "left";
      ctx.textBaseline = "middle";
      ctx.fillText(point.name, point.x - 1, point.y - 15);
    }
  });
};

// 查找点击位置的点位索引
const getPointAtPosition = (x, y) => {
  return points.value.findIndex(
    (point) =>
      x >= point.x &&
      x <= point.x + point.width &&
      y >= point.y &&
      y <= point.y + point.height
  );
};

// 存储当前绘画开始的点位索引
const startPointIndex = ref(-1);

// 鼠标按下事件
const handleMouseDown = (e) => {
  // 如果是左键点击
  if (e.button === 0) {
    const canvas = document.getElementById("myCanvas");
    const rect = canvas.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;

    // 如果处于绘画模式，检查是否在点位上点击才开始绘画
    if (isDrawing.value) {
      // 查找点击位置是否在某个点位上
      const pointIndex = getPointAtPosition(mouseX, mouseY);

      // 只有在点位上点击才能开始绘画
      if (pointIndex !== -1) {
        // 开始新的线段绘制
        isDrawingLine = true;
        // 记录起点点位索引
        startPointIndex.value = pointIndex;
        // 记录起点（使用点位中心点作为起点）
        const clickedPoint = points.value[pointIndex];
        const centerX = clickedPoint.x + clickedPoint.width / 2;
        const centerY = clickedPoint.y + clickedPoint.height / 2;
        currentDrawing = [{ x: centerX, y: centerY }];
        // 开始记录点位坐标
        currentPointCoordinates = [{ x: centerX, y: centerY }];

        // 显示提示信息
        console.log("已在点位上开始绘画");
        console.log(
          "开始绘画前 - freeDrawings长度:",
          freeDrawings.value.length
        );
      } else {
        // 如果不在点位上点击，不开始绘画并显示提示
        console.log("请在点位上开始绘画");
      }
      return;
    }

    // 查找点击位置的点位
    const pointIndex = getPointAtPosition(mouseX, mouseY);

    // 编辑模式下的拖拽功能
    if (!isEditing.value || disableDragging.value) return;

    draggingPointIndex = pointIndex;

    if (draggingPointIndex !== -1) {
      // 计算偏移量
      offsetX = mouseX - points.value[draggingPointIndex].x;
      offsetY = mouseY - points.value[draggingPointIndex].y;
    } else if (!isDrawing.value) {
      // 如果不是拖拽点位，检查是否可以点击选中线条

      // 如果鼠标悬停在线条上，直接使用悬停的线条作为选中的线条
      if (hoveredLineIndex !== -1) {
        selectedLineIndex = hoveredLineIndex;
        isDraggingLine = true;
        draggedLineIndex = hoveredLineIndex;
        draggedLineOffsetX = mouseX;
        draggedLineOffsetY = mouseY;
        hoveredLineIndex = -1; // 清除悬停状态
        drawCanvas();
        return;
      }

      // 如果没有悬停线条，进行正常的线条点击检测
      selectedLineIndex = -1; // 重置选中状态
      isDraggingLine = false;
      draggedLineIndex = -1;

      // 检查鼠标位置是否在线条上
      for (let i = 0; i < freeDrawings.value.length; i++) {
        const drawing = freeDrawings.value[i];

        if (drawing.length === 2) {
          if (drawing[0].isArc) {
            // 处理isArc类型的线条（只有两个点的圆弧连接）
            const start = drawing[0];
            const end = drawing[1];

            // 对于圆弧连接，使用更合理的检测方式
            // 创建圆弧的四个可能的中间点
            const cornerRadius =
              drawing[1].radius ||
              Math.min(Math.abs(end.x - start.x), Math.abs(end.y - start.y)) *
                0.4;
            let checkPoints = [];

            // 计算多个检查点来覆盖整个圆弧
            // 增加检查点数量以确保整个圆弧都能被检测到
            const steps = 12; // 将圆弧分成12个检查点，确保覆盖整个圆弧
            const centerX = (start.x + end.x) / 2;
            const centerY = (start.y + end.y) / 2;

            if (Math.abs(end.x - start.x) > Math.abs(end.y - start.y)) {
              // 水平为主的圆弧
              const radius = cornerRadius;
              // 确定圆弧的起始角度和结束角度
              let startAngle, endAngle;
              if (start.x < end.x && start.y < end.y) {
                // 从左下到右上的圆弧
                startAngle = Math.PI; // 180度
                endAngle = Math.PI * 1.5; // 270度
              } else if (start.x < end.x && start.y > end.y) {
                // 从左上到右下的圆弧
                startAngle = Math.PI * 0.5; // 90度
                endAngle = Math.PI; // 180度
              } else if (start.x > end.x && start.y < end.y) {
                // 从右下到左上的圆弧
                startAngle = 0; // 0度
                endAngle = Math.PI * 0.5; // 90度
              } else {
                // 从右上到左下的圆弧
                startAngle = Math.PI * 1.5; // 270度
                endAngle = Math.PI * 2; // 360度
              }

              // 计算圆弧上的多个检查点
              for (let j = 0; j <= steps; j++) {
                const angle =
                  startAngle + ((endAngle - startAngle) * j) / steps;
                const x = centerX + radius * Math.cos(angle);
                const y = centerY + radius * Math.sin(angle);
                checkPoints.push({ x, y });
              }
            } else {
              // 垂直为主的圆弧
              const radius = cornerRadius;
              // 确定圆弧的起始角度和结束角度
              let startAngle, endAngle;
              if (start.x < end.x && start.y < end.y) {
                // 从左下到右上的圆弧
                startAngle = Math.PI * 0.5; // 90度
                endAngle = Math.PI; // 180度
              } else if (start.x < end.x && start.y > end.y) {
                // 从左上到右下的圆弧
                startAngle = Math.PI; // 180度
                endAngle = Math.PI * 1.5; // 270度
              } else if (start.x > end.x && start.y < end.y) {
                // 从右下到左上的圆弧
                startAngle = 0; // 0度
                endAngle = Math.PI * 0.5; // 90度
              } else {
                // 从右上到左下的圆弧
                startAngle = Math.PI * 1.5; // 270度
                endAngle = Math.PI * 2; // 360度
              }

              // 计算圆弧上的多个检查点
              for (let j = 0; j <= steps; j++) {
                const angle =
                  startAngle + ((endAngle - startAngle) * j) / steps;
                const x = centerX + radius * Math.cos(angle);
                const y = centerY + radius * Math.sin(angle);
                checkPoints.push({ x, y });
              }
            }

            // 检查鼠标是否接近圆弧上的任何一个检查点（容差为15px）
            let isNearArc = false;
            for (const point of checkPoints) {
              const distance = Math.sqrt(
                Math.pow(mouseX - point.x, 2) + Math.pow(mouseY - point.y, 2)
              );
              if (distance <= 15) {
                isNearArc = true;
                break;
              }
            }

            // 如果检查点方法未检测到，尝试使用更直接的几何方法判断点是否在圆弧上
            if (!isNearArc) {
              // 计算鼠标到圆弧中心的距离
              const centerX = (start.x + end.x) / 2;
              const centerY = (start.y + end.y) / 2;
              const mouseToCenter = Math.sqrt(
                Math.pow(mouseX - centerX, 2) + Math.pow(mouseY - centerY, 2)
              );

              // 计算圆弧半径（近似值）
              const arcRadius =
                Math.min(Math.abs(end.x - start.x), Math.abs(end.y - start.y)) *
                0.4;

              // 如果鼠标距离圆弧中心的距离接近圆弧半径，并且鼠标在起点和终点之间的区域，则认为鼠标在圆弧上
              if (Math.abs(mouseToCenter - arcRadius) <= 20) {
                // 检查鼠标是否在起点和终点形成的矩形区域内
                const minX = Math.min(start.x, end.x) - 20;
                const maxX = Math.max(start.x, end.x) + 20;
                const minY = Math.min(start.y, end.y) - 20;
                const maxY = Math.max(start.y, end.y) + 20;

                if (
                  mouseX >= minX &&
                  mouseX <= maxX &&
                  mouseY >= minY &&
                  mouseY <= maxY
                ) {
                  isNearArc = true;
                }
              }
            }

            if (isNearArc) {
              isDraggingLine = true;
              draggedLineIndex = i;
              draggedLineOffsetX = mouseX;
              draggedLineOffsetY = mouseY;

              // 将圆弧连接转换为可以拖拽的多点线条
              const cornerRadius =
                drawing[1].radius ||
                Math.min(Math.abs(end.x - start.x), Math.abs(end.y - start.y)) *
                  0.4;

              // 根据起点和终点的相对位置创建中间点
              let midPoints = [];
              if (start.x < end.x) {
                // 起点在终点左侧
                if (start.y < end.y) {
                  // 起点在终点左下方
                  midPoints = [
                    { x: end.x - cornerRadius, y: start.y },
                    { x: end.x, y: start.y + cornerRadius },
                  ];
                } else {
                  // 起点在终点左上方
                  midPoints = [
                    { x: end.x - cornerRadius, y: start.y },
                    { x: end.x, y: start.y - cornerRadius },
                  ];
                }
              } else {
                // 起点在终点右侧
                if (start.y < end.y) {
                  // 起点在终点右下方
                  midPoints = [
                    { x: end.x + cornerRadius, y: start.y },
                    { x: end.x, y: start.y + cornerRadius },
                  ];
                } else {
                  // 起点在终点右上方
                  midPoints = [
                    { x: end.x + cornerRadius, y: start.y },
                    { x: end.x, y: start.y - cornerRadius },
                  ];
                }
              }

              // 更新线条为多点连接，去除isArc标志
              freeDrawings.value[i] = [start, ...midPoints, end];

              // 同时更新drawingCoordinateGroups中对应的线条
              for (let j = 0; j < drawingCoordinateGroups.value.length; j++) {
                const group = drawingCoordinateGroups.value[j];
                if (group.coordinates === drawing) {
                  drawingCoordinateGroups.value[j].coordinates = [
                    start,
                    ...midPoints,
                    end,
                  ];
                  break;
                }
              }

              drawCanvas();
              return;
            }
          } else {
            // 处理两点直线
            const start = drawing[0];
            const end = drawing[1];

            // 检查鼠标是否靠近直线（容差为15px，与圆弧保持一致）
            if (
              isPointOnLine(mouseX, mouseY, start.x, start.y, end.x, end.y, 15)
            ) {
              // 设置线条选中状态
              selectedLineIndex = i;
              isDraggingLine = true;
              draggedLineIndex = i;
              draggedLineOffsetX = mouseX;
              draggedLineOffsetY = mouseY;

              // 转换为多点线条以便拖拽
              if (drawing.length === 2) {
                const midX = (start.x + end.x) / 2;
                const midY = (start.y + end.y) / 2;
                const controlPoint = { x: midX, y: midY };
                freeDrawings.value[i] = [start, controlPoint, end];

                // 更新drawingCoordinateGroups
                for (let j = 0; j < drawingCoordinateGroups.value.length; j++) {
                  const group = drawingCoordinateGroups.value[j];
                  if (group.coordinates === drawing) {
                    drawingCoordinateGroups.value[j].coordinates = [
                      start,
                      controlPoint,
                      end,
                    ];
                    break;
                  }
                }
              }

              drawCanvas();
              return;
            }
          }
        } else if (drawing.length > 2) {
          // 处理多点线条
          // 检查鼠标是否在线条的某一段上
          for (let j = 0; j < drawing.length - 1; j++) {
            const start = drawing[j];
            const end = drawing[j + 1];

            // 检查鼠标是否靠近线段（容差为10px）
            if (
              isPointOnLine(mouseX, mouseY, start.x, start.y, end.x, end.y, 10)
            ) {
              isDraggingLine = true;
              draggedLineIndex = i;
              draggedLineOffsetX = mouseX;
              draggedLineOffsetY = mouseY;
              return;
            }
          }
        }
      }
    }
  }
};

// 处理鼠标离开画布事件
const handleMouseLeave = () => {
  // 重置鼠标悬停状态
  if (hoveredLineIndex !== -1) {
    hoveredLineIndex = -1;
    drawCanvas();
  }
  // 重置点位悬停状态
  if (hoveredPointIndex !== -1) {
    hoveredPointIndex = -1;
    drawCanvas();
  }
};

// 鼠标移动事件
const handleMouseMove = (e) => {
  const canvas = document.getElementById("myCanvas");
  const rect = canvas.getBoundingClientRect();
  const mouseX = e.clientX - rect.left;
  const mouseY = e.clientY - rect.top;

  // 非绘画状态下，检测鼠标是否悬停在线条上
  if (
    !isDrawing.value &&
    !isDrawingLine &&
    !isDraggingLine &&
    draggingPointIndex === -1
  ) {
    // 首先检查鼠标是否悬停在点位上
    const pointIndex = getPointAtPosition(mouseX, mouseY);

    // 如果鼠标悬停在点位上，不检测线条悬停，重置线条悬停状态
    if (pointIndex !== -1) {
      if (hoveredLineIndex !== -1) {
        hoveredLineIndex = -1;
        drawCanvas();
      }
      // 更新悬停点位索引
      if (hoveredPointIndex !== pointIndex) {
        hoveredPointIndex = pointIndex;
        drawCanvas();
      }
    } else {
      // 只有当鼠标没有悬停在点位上时，才检测线条悬停
      let newHoveredLineIndex = -1;

      // 检查是否有线条被鼠标悬停
      for (let i = 0; i < freeDrawings.value.length; i++) {
        const drawing = freeDrawings.value[i];

        // 处理两点直线
        if (drawing.length === 2) {
          if (drawing[0].isArc) {
            // 对于圆弧，使用现有的检查逻辑
            const start = drawing[0];
            const end = drawing[1];
            // 简化的圆弧检测
            if (
              isPointOnLine(mouseX, mouseY, start.x, start.y, end.x, end.y, 15)
            ) {
              newHoveredLineIndex = i;
              break;
            }
          } else {
            // 检查直线
            if (
              isPointOnLine(
                mouseX,
                mouseY,
                drawing[0].x,
                drawing[0].y,
                drawing[1].x,
                drawing[1].y,
                15
              )
            ) {
              newHoveredLineIndex = i;
              break;
            }
          }
        } else if (drawing.length > 2) {
          // 处理多点线条
          for (let j = 0; j < drawing.length - 1; j++) {
            if (
              isPointOnLine(
                mouseX,
                mouseY,
                drawing[j].x,
                drawing[j].y,
                drawing[j + 1].x,
                drawing[j + 1].y,
                10
              )
            ) {
              newHoveredLineIndex = i;
              break;
            }
          }
        }

        if (newHoveredLineIndex !== -1) break;
      }

      // 如果悬停的线条发生变化，重新绘制
      if (newHoveredLineIndex !== hoveredLineIndex) {
        hoveredLineIndex = newHoveredLineIndex;
        drawCanvas();
      }

      // 重置点位悬停状态
      if (hoveredPointIndex !== -1) {
        hoveredPointIndex = -1;
        drawCanvas();
      }
    }
  } else if (hoveredLineIndex !== -1) {
    // 如果正在拖拽或绘画，重置悬停状态
    hoveredLineIndex = -1;
    drawCanvas();
  }

  // 拖拽点位
  if (draggingPointIndex !== -1 && !disableDragging.value) {
    // 更新点位位置
    points.value[draggingPointIndex].x = mouseX - offsetX;
    points.value[draggingPointIndex].y = mouseY - offsetY;

    // 获取点位的新中心坐标
    const point = points.value[draggingPointIndex];
    const pointId = point.id;
    const newCenterX = point.x + point.width / 2;
    const newCenterY = point.y + point.height / 2;

    // 更新所有与该点位连接的线条
    drawingCoordinateGroups.value = drawingCoordinateGroups.value.map(
      (group) => {
        // 查找与当前点位相关的线条
        if (group.startPointId === pointId || group.endPointId === pointId) {
          // 创建新的线条副本以确保响应式更新
          const updatedDrawing = group.coordinates.map((point, index) => {
            // 深拷贝点对象
            const newPoint = { ...point };

            // 更新线条的起点或终点坐标
            if (group.startPointId === pointId && index === 0) {
              // 更新线条的起点
              newPoint.x = newCenterX;
              newPoint.y = newCenterY;
            }
            if (
              group.endPointId === pointId &&
              index === group.coordinates.length - 1
            ) {
              // 更新线条的终点
              newPoint.x = newCenterX;
              newPoint.y = newCenterY;
            }

            return newPoint;
          });

          // 直接更新freeDrawings数组中所有相关的线条
          // 不再依赖引用相等性检查，而是根据线条的起点和终点ID匹配
          for (let i = 0; i < freeDrawings.value.length; i++) {
            // 检查当前处理的线条是否是freeDrawings中的某个线条
            const drawing = freeDrawings.value[i];
            // 比较起点和终点的坐标来判断是否为同一线条
            // 对于两点直线，比较起点和终点坐标
            if (
              (drawing.length === 2 &&
                Math.abs(drawing[0].x - group.coordinates[0].x) < 1 &&
                Math.abs(drawing[0].y - group.coordinates[0].y) < 1 &&
                Math.abs(
                  drawing[1].x -
                    group.coordinates[group.coordinates.length - 1].x
                ) < 1 &&
                Math.abs(
                  drawing[1].y -
                    group.coordinates[group.coordinates.length - 1].y
                ) < 1) ||
              (Math.abs(drawing[1].x - group.coordinates[0].x) < 1 &&
                Math.abs(drawing[1].y - group.coordinates[0].y) < 1 &&
                Math.abs(
                  drawing[0].x -
                    group.coordinates[group.coordinates.length - 1].x
                ) < 1 &&
                Math.abs(
                  drawing[0].y -
                    group.coordinates[group.coordinates.length - 1].y
                ) < 1)
            ) {
              freeDrawings.value[i] = updatedDrawing;
            }
            // 对于多点线条，使用更精确的匹配方法
            else if (
              (drawing.length > 2 &&
                drawing.length === group.coordinates.length &&
                Math.abs(drawing[0].x - group.coordinates[0].x) < 1 &&
                Math.abs(drawing[0].y - group.coordinates[0].y) < 1 &&
                Math.abs(
                  drawing[drawing.length - 1].x -
                    group.coordinates[group.coordinates.length - 1].x
                ) < 1 &&
                Math.abs(
                  drawing[drawing.length - 1].y -
                    group.coordinates[group.coordinates.length - 1].y
                ) < 1) ||
              (Math.abs(
                drawing[drawing.length - 1].x - group.coordinates[0].x
              ) < 1 &&
                Math.abs(
                  drawing[drawing.length - 1].y - group.coordinates[0].y
                ) < 1 &&
                Math.abs(
                  drawing[0].x -
                    group.coordinates[group.coordinates.length - 1].x
                ) < 1 &&
                Math.abs(
                  drawing[0].y -
                    group.coordinates[group.coordinates.length - 1].y
                ) < 1)
            ) {
              freeDrawings.value[i] = updatedDrawing;
            }
          }

          // 同时也更新savedDrawingCoordinateGroups中的相关线条
          // 确保在结束绘画后拖拽点位时线条也能正确跟随移动
          for (let i = 0; i < savedDrawingCoordinateGroups.value.length; i++) {
            const savedGroup = savedDrawingCoordinateGroups.value[i];
            if (
              savedGroup.startPointId === pointId ||
              savedGroup.endPointId === pointId
            ) {
              // 创建新的线条副本并更新起点/终点坐标
              const savedUpdatedDrawing = savedGroup.coordinates.map(
                (point, index) => {
                  // 深拷贝点对象
                  const newPoint = { ...point };

                  // 更新线条的起点或终点坐标
                  if (savedGroup.startPointId === pointId && index === 0) {
                    // 更新线条的起点
                    newPoint.x = newCenterX;
                    newPoint.y = newCenterY;
                  }
                  if (
                    savedGroup.endPointId === pointId &&
                    index === savedGroup.coordinates.length - 1
                  ) {
                    // 更新线条的终点
                    newPoint.x = newCenterX;
                    newPoint.y = newCenterY;
                  }

                  return newPoint;
                }
              );

              savedDrawingCoordinateGroups.value[i] = {
                ...savedGroup,
                coordinates: savedUpdatedDrawing,
              };
              // 不要break，继续更新所有匹配的线条
            }
          }

          // 返回更新后的组，保持点位关联
          return {
            ...group,
            coordinates: updatedDrawing,
          };
        }
        return group;
      }
    );

    // 重新绘制
    drawCanvas();
  } else if (
    isDraggingLine &&
    draggedLineIndex !== -1 &&
    !disableDragging.value
  ) {
    // 拖拽线条改变曲线形状 - 在任何状态下都可以拖拽线条，包括非绘画状态

    // 计算鼠标移动的距离
    const dx = mouseX - draggedLineOffsetX;
    const dy = mouseY - draggedLineOffsetY;

    if (dx !== 0 || dy !== 0) {
      const drawing = freeDrawings.value[draggedLineIndex];

      // 找到对应的drawingCoordinateGroup，不再依赖引用相等性检查
      let correspondingGroup = null;
      // 通过线条的长度和起点终点坐标来匹配对应的group
      for (let j = 0; j < drawingCoordinateGroups.value.length; j++) {
        const group = drawingCoordinateGroups.value[j];
        // 对于两点直线，比较起点和终点坐标
        if (
          (group.coordinates.length === drawing.length &&
            Math.abs(group.coordinates[0].x - drawing[0].x) < 1 &&
            Math.abs(group.coordinates[0].y - drawing[0].y) < 1 &&
            Math.abs(
              group.coordinates[group.coordinates.length - 1].x -
                drawing[drawing.length - 1].x
            ) < 1 &&
            Math.abs(
              group.coordinates[group.coordinates.length - 1].y -
                drawing[drawing.length - 1].y
            ) < 1) ||
          (Math.abs(group.coordinates[1].x - drawing[0].x) < 1 &&
            Math.abs(group.coordinates[1].y - drawing[0].y) < 1 &&
            Math.abs(group.coordinates[0].x - drawing[drawing.length - 1].x) <
              1 &&
            Math.abs(group.coordinates[0].y - drawing[drawing.length - 1].y) <
              1)
        ) {
          correspondingGroup = group;
          break;
        }
      }

      // 处理线条拖拽
      if (drawing.length === 2) {
        // 对于两点直线，先转换为多点线条
        const start = { ...drawing[0] };
        const end = { ...drawing[1] };

        // 计算中点
        const midX = (start.x + end.x) / 2;
        const midY = (start.y + end.y) / 2;

        // 在中点创建一个新的控制点，并应用拖拽偏移
        const controlPoint = { x: midX + dx, y: midY + dy };

        // 确保线条的起点和终点始终与点位连接
        let updatedStart = { ...start };
        let updatedEnd = { ...end };

        // 如果找到对应的group，更新起点和终点坐标为点位中心
        if (
          correspondingGroup &&
          correspondingGroup.startPointId &&
          correspondingGroup.endPointId
        ) {
          // 查找对应的起点和终点点位
          const startPoint = points.value.find(
            (p) => p.id === correspondingGroup.startPointId
          );
          const endPoint = points.value.find(
            (p) => p.id === correspondingGroup.endPointId
          );

          // 如果找到对应的点位，更新线条的起点和终点位置
          if (startPoint) {
            updatedStart.x = startPoint.x + startPoint.width / 2;
            updatedStart.y = startPoint.y + startPoint.height / 2;
          }
          if (endPoint) {
            updatedEnd.x = endPoint.x + endPoint.width / 2;
            updatedEnd.y = endPoint.y + endPoint.height / 2;
          }
        }

        // 将直线转换为具有控制点的线条
        const updatedDrawing = [updatedStart, controlPoint, updatedEnd];
        freeDrawings.value[draggedLineIndex] = updatedDrawing;

        // 同时更新drawingCoordinateGroups中对应的线条，并保持点位关联
        if (correspondingGroup) {
          // 保留原始的起点和终点点位ID
          const startPointId = correspondingGroup.startPointId;
          const endPointId = correspondingGroup.endPointId;

          // 更新坐标但保留点位ID关联，不再依赖引用相等性检查
          drawingCoordinateGroups.value = drawingCoordinateGroups.value.map(
            (group) => {
              if (
                group.startPointId === startPointId &&
                group.endPointId === endPointId
              ) {
                return {
                  ...group,
                  coordinates: updatedDrawing,
                };
              }
              return group;
            }
          );

          // 同时也更新savedDrawingCoordinateGroups中的相关线条
          // 确保在结束绘画后拖拽线条时也能正确更新
          for (let i = 0; i < savedDrawingCoordinateGroups.value.length; i++) {
            const savedGroup = savedDrawingCoordinateGroups.value[i];
            if (
              savedGroup.startPointId === correspondingGroup.startPointId &&
              savedGroup.endPointId === correspondingGroup.endPointId
            ) {
              savedDrawingCoordinateGroups.value[i] = {
                ...savedGroup,
                coordinates: updatedDrawing,
              };
              break;
            }
          }
        }

        // 更新偏移量
        draggedLineOffsetX = mouseX;
        draggedLineOffsetY = mouseY;

        // 重新绘制
        drawCanvas();
        return;
      }

      // 移动所有中间点（如果有）
      if (drawing.length > 2) {
        // 只移动中间点，保留起点和终点
        for (let i = 1; i < drawing.length - 1; i++) {
          drawing[i].x += dx;
          drawing[i].y += dy;
        }

        // 更新偏移量
        draggedLineOffsetX = mouseX;
        draggedLineOffsetY = mouseY;

        // 强制更新drawingCoordinateGroups中的对应线条，并保持点位关联，不再依赖引用相等性检查
        // 找到对应的group
        let matchingGroupIndex = -1;
        let correspondingGroup = null;
        for (let j = 0; j < drawingCoordinateGroups.value.length; j++) {
          const group = drawingCoordinateGroups.value[j];
          if (
            (group.coordinates.length === drawing.length &&
              Math.abs(group.coordinates[0].x - drawing[0].x) < 1 &&
              Math.abs(group.coordinates[0].y - drawing[0].y) < 1 &&
              Math.abs(
                group.coordinates[group.coordinates.length - 1].x -
                  drawing[drawing.length - 1].x
              ) < 1 &&
              Math.abs(
                group.coordinates[group.coordinates.length - 1].y -
                  drawing[drawing.length - 1].y
              ) < 1) ||
            (Math.abs(group.coordinates[1].x - drawing[0].x) < 1 &&
              Math.abs(group.coordinates[1].y - drawing[0].y) < 1 &&
              Math.abs(group.coordinates[0].x - drawing[drawing.length - 1].x) <
                1 &&
              Math.abs(group.coordinates[0].y - drawing[drawing.length - 1].y) <
                1)
          ) {
            matchingGroupIndex = j;
            correspondingGroup = group;
            break;
          }
        }

        if (matchingGroupIndex !== -1) {
          // 确保线条的起点和终点始终与点位连接
          // 查找对应的起点和终点点位
          let startPoint = null;
          let endPoint = null;
          if (
            correspondingGroup &&
            correspondingGroup.startPointId &&
            correspondingGroup.endPointId
          ) {
            startPoint = points.value.find(
              (p) => p.id === correspondingGroup.startPointId
            );
            endPoint = points.value.find(
              (p) => p.id === correspondingGroup.endPointId
            );
          }

          // 如果找到对应的点位，更新线条的起点和终点位置
          if (startPoint) {
            drawing[0].x = startPoint.x + startPoint.width / 2;
            drawing[0].y = startPoint.y + startPoint.height / 2;
          }
          if (endPoint) {
            drawing[drawing.length - 1].x = endPoint.x + endPoint.width / 2;
            drawing[drawing.length - 1].y = endPoint.y + endPoint.height / 2;
          }

          // 创建新的数组引用以确保响应式更新，同时保留起点和终点点位ID
          drawingCoordinateGroups.value = drawingCoordinateGroups.value.map(
            (group, index) => {
              if (index === matchingGroupIndex) {
                return {
                  ...group,
                  coordinates: [...drawing],
                };
              }
              return group;
            }
          );

          // 同时也更新savedDrawingCoordinateGroups中的相关线条
          // 确保在结束绘画后拖拽线条时也能正确更新
          const originalGroup =
            drawingCoordinateGroups.value[matchingGroupIndex];
          for (let i = 0; i < savedDrawingCoordinateGroups.value.length; i++) {
            const savedGroup = savedDrawingCoordinateGroups.value[i];
            if (
              savedGroup.startPointId === originalGroup.startPointId &&
              savedGroup.endPointId === originalGroup.endPointId
            ) {
              savedDrawingCoordinateGroups.value[i] = {
                ...savedGroup,
                coordinates: [...drawing],
              };
              break;
            }
          }
        }

        // 重新绘制
        drawCanvas();
      }
    }
  }
  // 直线连接绘画
  else if (isDrawingLine && isDrawing.value) {
    const canvas = document.getElementById("myCanvas");
    const rect = canvas.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;

    // 清除旧的鼠标点，只保留起点和当前鼠标位置，实现直线跟随
    if (currentDrawing.length > 1) {
      currentDrawing.splice(1);
    }
    currentDrawing.push({ x: mouseX, y: mouseY });

    // 重新绘制
    drawCanvas();
  }
};

// 鼠标抬起事件
const handleMouseUp = (e) => {
  // 结束拖拽
  draggingPointIndex = -1;
  // 鼠标左键松开时关闭拖拽状态
  isDraggingLine = false;
  draggedLineIndex = -1;
  selectedLineIndex = -1; // 同时清除选中状态

  // 结束绘画
  if (isDrawingLine && isDrawing.value) {
    isDrawingLine = false;

    // 如果当前正在绘制的线条有两个点以上
    if (currentDrawing.length >= 2) {
      // 当没有传递事件对象时，从最后一个点获取位置
      if (!e) {
        // 直接使用最后一个点的位置
        currentDrawing = [];
        return;
      }

      const canvas = document.getElementById("myCanvas");
      const rect = canvas.getBoundingClientRect();
      // 获取当前鼠标位置作为结束点
      const mouseX = e.clientX - rect.left;
      const mouseY = e.clientY - rect.top;

      // 检查结束点是否在某个点位上
      const endPointIndex = getPointAtPosition(mouseX, mouseY);

      if (endPointIndex !== -1) {
        // 如果结束点在点位上，将线条添加到自由绘制线条数组中
        const endPoint = points.value[endPointIndex];
        const endPointCenterX = endPoint.x + endPoint.width / 2;
        const endPointCenterY = endPoint.y + endPoint.height / 2;

        // 将线条终点调整为点位中心
        currentDrawing[currentDrawing.length - 1] = {
          x: endPointCenterX,
          y: endPointCenterY,
        };

        // 只添加到freeDrawings数组中，不再添加到connections数组，避免重复绘制
        const startIndex = startPointIndex.value;
        freeDrawings.value.push([...currentDrawing]);
        // 将线条信息添加到drawingCoordinateGroups，以便后续可以引用
        drawingCoordinateGroups.value.push({
          startPointId: points.value[startIndex].id,
          endPointId: points.value[endPointIndex].id,
          coordinates: [...currentDrawing],
        });
        // 确保currentPointCoordinates只包含起点和终点（均为点位中心）
        const startPoint = points.value[startIndex];
        const startPointCenterX = startPoint.x + startPoint.width / 2;
        const startPointCenterY = startPoint.y + startPoint.height / 2;

        currentPointCoordinates = [
          { x: startPointCenterX, y: startPointCenterY },
          { x: endPointCenterX, y: endPointCenterY },
        ];

        console.log("在点位上结束绘画，已保存线条");
        console.log("保存后 - freeDrawings长度:", freeDrawings.value.length);
        console.log("添加的连接:", { startIndex, endPointIndex });
        console.log("当前所有线条:", freeDrawings.value.length + " 条");
      } else {
        // 如果结束点不在点位上，取消当前绘制的线条
        console.log("请在点位上结束绘画");
      }

      currentDrawing = [];
      // 连线完成后，清空当前绘画点坐标，确保下次绘画时重新开始
      currentPointCoordinates = [];
      // 重绘画布，确保点位选中样式立即关闭
      drawCanvas();
    }
  }
};

// 右键点击事件（显示菜单）
const handleContextMenu = (e) => {
  // 只有在编辑模式下、不在绘画模式下、且未锁定拖拽状态时才允许右键菜单
  if (!isEditing.value || isDrawing.value || disableDragging.value) return;

  e.preventDefault(); // 阻止默认右键菜单

  const canvas = document.getElementById("myCanvas");
  const rect = canvas.getBoundingClientRect();
  const mouseX = e.clientX - rect.left;
  const mouseY = e.clientY - rect.top;

  const pointIndex = getPointAtPosition(mouseX, mouseY);
  if (pointIndex !== -1) {
    // 显示右键菜单
    contextMenu.value = {
      show: true,
      x: e.clientX,
      y: e.clientY,
      pointIndex: pointIndex,
    };
  }
};

// 删除点位
const deletePoint = () => {
  if (contextMenu.value.pointIndex !== -1) {
    const deletedIndex = contextMenu.value.pointIndex;
    const deletedPoint = points.value[deletedIndex];
    const deletedPointId = deletedPoint.id;

    // 删除点位
    points.value.splice(deletedIndex, 1);

    // 同时删除与该点位相关的线条（drawingCoordinateGroups和freeDrawings数组）
    // 先记录哪些索引需要删除
    const indexesToRemove = [];
    drawingCoordinateGroups.value.forEach((group, index) => {
      if (
        group.startPointId === deletedPointId ||
        group.endPointId === deletedPointId
      ) {
        indexesToRemove.push(index);
      }
    });

    // 从后往前删除，避免索引变化问题
    for (let i = indexesToRemove.length - 1; i >= 0; i--) {
      const index = indexesToRemove[i];
      drawingCoordinateGroups.value.splice(index, 1);
      freeDrawings.value.splice(index, 1);
    }

    // 重新绘制画布
    drawCanvas();
  }
  // 关闭菜单
  contextMenu.value.show = false;
};

// 关闭右键菜单
const closeContextMenu = () => {
  contextMenu.value.show = false;
};

// 点击遮罩层关闭右键菜单和编辑名称弹窗
const handleOverlayClick = () => {
  closeContextMenu();
  cancelEditName();
};

// 编辑点位名称
const editPointName = () => {
  // 关闭右键菜单
  contextMenu.value.show = false;

  // 显示编辑名称弹窗
  editNameModal.value = {
    show: true,
    x: contextMenu.value.x,
    y: contextMenu.value.y,
    pointIndex: contextMenu.value.pointIndex,
    name: points.value[contextMenu.value.pointIndex].name || "",
  };

  // 延迟设置焦点，确保DOM已经渲染
  setTimeout(() => {
    const inputRef = document.querySelector(".name-input");
    if (inputRef) {
      inputRef.focus();
    }
  }, 10);
};

// 保存点位名称
const savePointName = () => {
  if (editNameModal.value.pointIndex !== -1) {
    points.value[editNameModal.value.pointIndex].name =
      editNameModal.value.name;
    drawCanvas();
  }
  // 关闭编辑名称弹窗
  editNameModal.value.show = false;
};

// 取消编辑点位名称
const cancelEditName = () => {
  // 关闭编辑名称弹窗
  editNameModal.value.show = false;
};

// 清空点位
const clearPoints = () => {
  if (confirm("确定要清空所有点位吗？这将删除所有点位和相关连线。")) {
    points.value = [];
    freeDrawings.value = [];
    drawingCoordinateGroups.value = [];
    savedDrawingCoordinateGroups.value = [];

    // 重置按钮显示状态到初始状态
    isDrawing.value = false;
    isEditing.value = true;
    showDrawingButtons.value = true;
    showUndoButton.value = false;
    showSaveLayerButton.value = false; // 隐藏保存图层按钮

    // 重置拖拽相关状态
    draggingPointIndex = -1;
    offsetX = 0;
    offsetY = 0;
    isDraggingLine = false;
    draggedLineIndex = -1;
    draggedLineOffsetX = 0;
    draggedLineOffsetY = 0;
    selectedLineIndex = -1;
    hoveredLineIndex = -1;
    hoveredPointIndex = -1;
    disableDragging.value = false;

    // 重置轨迹展示相关状态
    layerPointIds.value = ""; // 清空点位ID输入框
    showTrajectoryInput.value = false; // 隐藏轨迹输入框和按钮

    drawCanvas();
  }
};

// 保存图层
const saveLayer = () => {
  // 清空提示文本
  infoTextType.value = "";

  // 保存当前的点位和线条数据的深拷贝
  const layerData = {
    points: JSON.parse(JSON.stringify(points.value)),
    freeDrawings: JSON.parse(JSON.stringify(freeDrawings.value)),
    drawingCoordinateGroups: JSON.parse(
      JSON.stringify(drawingCoordinateGroups.value)
    ),
    timestamp: new Date().toISOString(),
  };
  // 打印存储的线条坐标
  console.log("当前存储的线条坐标:", savedDrawingCoordinateGroups.value);

  console.log("当前保存的点位和线条数据", layerData);

  // 将图层数据添加到已保存图层数组
  savedLayers.value.push(layerData);

  // 隐藏所有线条
  showLines.value = false;

  // 禁止点位移动
  disableDragging.value = true;

  // 重新绘制画布以反映线条隐藏状态
  drawCanvas();

  // 显示轨迹输入框和按钮
  showTrajectoryInput.value = true;

  console.log("图层已保存，共保存了", savedLayers.value.length, "个图层");
  alert("图层已保存，线条暂时隐藏，点位已锁定");
};

// 计算线条长度（用于路径查找）
const calculateLineLength = (coordinates) => {
  let length = 0;
  for (let i = 0; i < coordinates.length - 1; i++) {
    const dx = coordinates[i + 1].x - coordinates[i].x;
    const dy = coordinates[i + 1].y - coordinates[i].y;
    length += Math.sqrt(dx * dx + dy * dy);
  }
  return length;
};

// 使用Dijkstra算法查找两点之间的最短路径
const findShortestPath = (startId, endId, allLines) => {
  // 构建图结构
  const graph = new Map();
  const lineMap = new Map(); // 存储连接的线条信息

  // 初始化图
  points.value.forEach((point) => {
    graph.set(point.id, []);
  });

  // 添加边到图中
  allLines.forEach((line) => {
    const startId = line.startPointId;
    const endId = line.endPointId;
    const length = calculateLineLength(line.coordinates);

    // 添加正向边和反向边（因为线条是双向的）
    graph.get(startId).push({ id: endId, length, line });
    graph.get(endId).push({ id: startId, length, line });

    // 存储线条信息
    const key1 = `${startId}-${endId}`;
    const key2 = `${endId}-${startId}`;
    lineMap.set(key1, line);
    lineMap.set(key2, line);
  });

  // Dijkstra算法实现
  const distances = new Map();
  const previous = new Map();
  const visited = new Set();

  // 初始化距离为无穷大
  points.value.forEach((point) => {
    distances.set(point.id, Infinity);
  });
  distances.set(startId, 0);

  // 优先队列（使用数组模拟）
  const queue = [...points.value.map((point) => point.id)];

  while (queue.length > 0) {
    // 找到距离最小的节点
    queue.sort((a, b) => distances.get(a) - distances.get(b));
    const current = queue.shift();

    if (current === endId) break; // 找到目标节点，提前退出
    if (visited.has(current)) continue;

    visited.add(current);

    // 遍历当前节点的所有邻居
    const neighbors = graph.get(current) || [];
    for (const neighbor of neighbors) {
      if (visited.has(neighbor.id)) continue;

      const newDistance = distances.get(current) + neighbor.length;
      if (newDistance < distances.get(neighbor.id)) {
        distances.set(neighbor.id, newDistance);
        previous.set(neighbor.id, { id: current, line: neighbor.line });
      }
    }
  }

  // 构建路径
  const path = [];
  let current = endId;

  while (previous.has(current)) {
    const prev = previous.get(current);
    path.unshift(prev.line); // 将线条添加到路径开头
    current = prev.id;
  }

  // 检查是否找到路径
  if (path.length === 0 && startId !== endId) {
    return null; // 没有找到路径
  }

  return path;
};

// 展示轨迹功能
const showTrajectory = () => {
  // 清空提示文本
  infoTextType.value = "";

  if (!layerPointIds.value.trim()) {
    alert("请至少输入一个点位ID");
    return;
  }
  // 清空当前显示的线条
  freeDrawings.value = [];
  drawingCoordinateGroups.value = [];
  // 设置禁止拖拽
  disableDragging.value = true;
  console.log("轨迹展示后，点位和线条的拖拽功能已被禁止");

  // 解析输入的点位ID
  const pointIds = layerPointIds.value
    .split("，")
    .map((id) => id.trim())
    .filter((id) => id);

  if (pointIds.length === 0) {
    alert("请输入有效的点位ID");
    return;
  }

  console.log(
    "开始展示轨迹 - 输入点位ID数量:",
    pointIds.length,
    "保存的图层数量:",
    savedLayers.value.length
  );

  // 保存输入点位的有效坐标和完整信息
  const validPoints = [];
  let allPointsExist = true;
  let straightLinesAdded = false;
  let shortestPathAdded = false;

  // 查找并保存所有输入点位的完整信息
  pointIds.forEach((id, index) => {
    // 由于ID现在是三位数字，直接进行精确匹配
    const point = points.value.find((p) => p.id.toString() === id.toString());
    if (!point) {
      allPointsExist = false;
    } else {
      const centerX = point.x + point.width / 2;
      const centerY = point.y + point.height / 2;
      validPoints.push({
        x: centerX,
        y: centerY,
        id: point.id,
        fullPoint: point,
      });
    }
  });

  // 验证所有点位是否存在
  // if (!allPointsExist) {
  //   alert("部分轨迹点位ID不存在，请检查输入");
  //   return;
  // }

  // 如果有多个点位，按照输入顺序进行连接
  if (validPoints.length >= 2) {
    // 合并所有保存图层中的线条信息
    let allSavedDrawingCoordinateGroups = [];
    console.log("展示轨迹前，保存的图层数量:", savedLayers.value);
    savedLayers.value.forEach((layer) => {
      allSavedDrawingCoordinateGroups = [
        ...allSavedDrawingCoordinateGroups,
        ...layer.drawingCoordinateGroups,
      ];
    });

    for (let i = 0; i < validPoints.length - 1; i++) {
      const startPoint = validPoints[i];
      const endPoint = validPoints[i + 1];

      // 检查是否有保存的线条直接连接
      let foundDirectLine = false;
      for (const group of allSavedDrawingCoordinateGroups) {
        // 检查是否有从startPoint到endPoint或endPoint到startPoint的曲线
        if (
          (group.startPointId === startPoint.id &&
            group.endPointId === endPoint.id) ||
          (group.startPointId === endPoint.id &&
            group.endPointId === startPoint.id)
        ) {
          freeDrawings.value.push([...group.coordinates]);
          drawingCoordinateGroups.value.push({
            startPointId: startPoint.id,
            endPointId: endPoint.id,
            coordinates: [...group.coordinates],
          });
          foundDirectLine = true;
          break;
        }
      }

      // 如果没有找到直接连接，尝试查找最短路径
      if (!foundDirectLine) {
        const shortestPath = findShortestPath(
          startPoint.id,
          endPoint.id,
          allSavedDrawingCoordinateGroups
        );

        if (shortestPath && shortestPath.length > 0) {
          // 添加最短路径的所有线条
          shortestPath.forEach((line) => {
            // 检查线条是否已经添加过
            const isLineExist = drawingCoordinateGroups.value.some(
              (existingLine) =>
                (existingLine.startPointId === line.startPointId &&
                  existingLine.endPointId === line.endPointId) ||
                (existingLine.startPointId === line.endPointId &&
                  existingLine.endPointId === line.startPointId)
            );

            if (!isLineExist) {
              freeDrawings.value.push([...line.coordinates]);
              drawingCoordinateGroups.value.push({
                startPointId: line.startPointId,
                endPointId: line.endPointId,
                coordinates: [...line.coordinates],
              });
            }
          });
          shortestPathAdded = true;
        } else {
          // 如果没有找到任何路径，使用直线连接
          const lineCoordinates = [
            { x: startPoint.x, y: startPoint.y },
            { x: endPoint.x, y: endPoint.y },
          ];
          freeDrawings.value.push(lineCoordinates);
          drawingCoordinateGroups.value.push({
            startPointId: startPoint.id,
            endPointId: endPoint.id,
            coordinates: lineCoordinates,
          });
          straightLinesAdded = true;
        }
      }
    }

    let message = "已按照输入顺序展示轨迹";
    if (shortestPathAdded) {
      message += "，部分点位之间使用最短路径连接";
    }
    if (straightLinesAdded) {
      message += "，部分点位之间使用直线连接";
    } else if (!shortestPathAdded) {
      message += "，全部使用已保存的线条连接";
    }
    alert(message);
  }

  // 显示线条
  showLines.value = true;

  // 重新绘制画布
  drawCanvas();
  console.log("展示轨迹完成 - 显示线条数量:", freeDrawings.value.length);
};

// 开始绘画
const startDrawing = () => {
  // 检查canvas中是否有点位且点位必须有两个
  if (points.value.length < 2) {
    alert("请添加至少两个点位后再开始连线");
    return;
  }

  // 设置提示文本类型
  infoTextType.value = "startDrawing";

  isDrawing.value = true;
  isDrawingLine = false;
  currentDrawing = [];
  // 显示撤销按钮
  showUndoButton.value = true;
  // 隐藏添加点位按钮
  showDrawingButtons.value = false;
};

// 查找点位ID对应的索引
const getPointByCoordinates = (x, y) => {
  // 查找最接近指定坐标的点位
  let closestPoint = null;
  let minDistance = Infinity;

  points.value.forEach((point) => {
    const pointCenterX = point.x + point.width / 2;
    const pointCenterY = point.y + point.height / 2;
    const distance = Math.sqrt(
      Math.pow(x - pointCenterX, 2) + Math.pow(y - pointCenterY, 2)
    );

    if (distance < minDistance) {
      minDistance = distance;
      closestPoint = point;
    }
  });

  return closestPoint;
};

// 结束绘画
const endDrawing = () => {
  // 检查canvas中是否有连线
  if (freeDrawings.value.length === 0) {
    alert("请先绘制连线后再调整点位连线");
    return;
  }

  // 设置提示文本类型
  infoTextType.value = "adjustDrawing";

  // 获取canvas中的点位信息
  const canvasPoints = points.value.map((point) => ({
    id: point.id,
    x: point.x,
    y: point.y,
    width: point.width,
    height: point.height,
    color: point.color,
  }));
  console.log("points", canvasPoints);

  // 恢复原始结束绘画逻辑
  isDrawing.value = false;
  isDrawingLine = false;

  // 隐藏撤销按钮
  showUndoButton.value = false;
  // 隐藏添加点位和开始连线按钮
  showDrawingButtons.value = false;

  // 保存所有线条坐标到savedDrawingCoordinateGroups
  if (drawingCoordinateGroups.value.length > 0) {
    // 将当前线条坐标组添加到保存的数组中
    savedDrawingCoordinateGroups.value = [
      ...savedDrawingCoordinateGroups.value,
      ...drawingCoordinateGroups.value,
    ];
    console.log(
      "已保存线条坐标，总保存线条数:",
      savedDrawingCoordinateGroups.value.length
    );
  }

  // 重新绘制画布
  drawCanvas();

  // 显示保存图层按钮
  showSaveLayerButton.value = true;

  console.log("结束绘画模式 - 点位数量:", points.value.length);
  console.log("结束绘画模式 - 显示线条数量:", freeDrawings.value.length);
  console.log(
    "结束绘画模式 - 保存线条数量:",
    savedDrawingCoordinateGroups.value.length
  );
};

// 检查点是否在线段上（带容差）
const isPointOnLine = (px, py, x1, y1, x2, y2, tolerance = 5) => {
  // 计算点到线段的距离
  const A = px - x1;
  const B = py - y1;
  const C = x2 - x1;
  const D = y2 - y1;

  const dot = A * C + B * D;
  const lenSq = C * C + D * D;
  let param = -1;

  if (lenSq !== 0) {
    param = dot / lenSq;
  }

  let xx, yy;

  if (param < 0) {
    xx = x1;
    yy = y1;
  } else if (param > 1) {
    xx = x2;
    yy = y2;
  } else {
    xx = x1 + param * C;
    yy = y1 + param * D;
  }

  const dx = px - xx;
  const dy = py - yy;
  return Math.sqrt(dx * dx + dy * dy) <= tolerance;
};

// 撤销上一次绘画
const undoDrawing = () => {
  // 清空提示文本
  infoTextType.value = "";

  if (freeDrawings.value.length > 0) {
    // 移除最后一次绘制的线条
    freeDrawings.value.pop();
    // 如果有对应的坐标组，也一并移除
    if (drawingCoordinateGroups.value.length > 0) {
      drawingCoordinateGroups.value.pop();
    }
    // 重新绘制画布以反映撤销操作
    drawCanvas();
    console.log("已撤销上一次绘画操作");
  }
};
</script>

<template>
  <div class="container"> 
    <!-- 主内容区 - 包含工具栏和画布 -->
    <div class="main-content">
      <!-- 左侧竖向工具栏 -->
      <div class="toolbar" :class="{ 'toolbar-disabled': !isDrawing && !showDrawingButtons }">
        <div class="toolbar-title">可用点位</div>
        <!-- 可拖拽的点位 -->
        <div
          class="draggable-point"
          :draggable="isDrawing || showDrawingButtons"
          @dragstart="handleDragStart"
          :style="{ backgroundColor: '#4ECDC4' }"
        ></div>
        <div
          class="draggable-point"
          :draggable="isDrawing || showDrawingButtons"
          @dragstart="handleDragStart"
          :style="{ backgroundColor: '#FF6B6B' }"
        ></div>
        <div
          class="draggable-point"
          :draggable="isDrawing || showDrawingButtons"
          @dragstart="handleDragStart"
          :style="{ backgroundColor: '#45B7D1' }"
        ></div>
        <div
          class="draggable-point"
          :draggable="isDrawing || showDrawingButtons"
          @dragstart="handleDragStart"
          :style="{ backgroundColor: '#96CEB4' }"
        ></div>
      </div>

      <!-- 画布和按钮区域 -->
      <div class="canvas-container">
            <h3>轨迹绘制工具</h3>
        <div class="button-group">
          <!-- <button
            v-if="showDrawingButtons"
            @click="addPoint"
            class="add-btn"
            :disabled="!isEditing"
          >
            添加点位
          </button> -->

          <button
            v-if="showDrawingButtons && isEditing && !isDrawing"
            @click="startDrawing"
            class="draw-btn"
          >
            开始连线
          </button>
          <button v-if="isDrawing" @click="endDrawing" class="stop-draw-btn">
            调整点位连线
          </button>
          <button
            v-if="showUndoButton && freeDrawings.length > 0 && !isDrawingLine"
            @click="undoDrawing"
            class="undo-btn"
          >
            撤销连线
          </button>
          <button
            v-if="showSaveLayerButton && !showTrajectoryInput"
            @click="saveLayer"
            class="save-layer-btn"
            :disabled="isDrawing || isDrawingLine"
          >
            保存图层
          </button>
          <!-- 图层轨迹展示控制区域 -->
          <div v-if="showTrajectoryInput" class="render-control">
            <input
              v-model="layerPointIds"
              type="text"
              placeholder="输入图层点位ID，多个ID以逗号分隔"
              class="render-input"
            />
            <button @click="showTrajectory" class="render-btn">展示轨迹</button>
          </div>
          <!-- 新增按钮 -->
          <button
            @click="clearPoints"
            class="clear-btn" 
          >
            重新绘制
          </button>
        </div>
        <canvas
          id="myCanvas"
          width="963"
          height="666"
          class="canvas"
          :data-editing="isEditing"
          :data-drawing="isDrawing"
          @mousedown="handleMouseDown"
          @mousemove="handleMouseMove"
          @mouseup="handleMouseUp"
          @contextmenu="handleContextMenu"
          @mouseleave="handleMouseLeave"
          @dragover="handleDragOver"
          @drop="handleDrop"
        ></canvas>
      </div>
    </div>
    <p class="info" v-if="infoTextType">
      <span v-if="infoTextType === 'addPoint'"
        >添加点位：点击按钮添加点位，点击并拖动点位可以移动它们，右键点击点位可以打开菜单。</span
      >
      <span v-else-if="infoTextType === 'startDrawing'"
        >连线模式：鼠标移动到点位上，按住鼠标左键移动至另一个点位，松开鼠标左键自动连线。</span
      >
      <span v-else-if="infoTextType === 'adjustDrawing'"
        >鼠标移动到点位上，按住鼠标左键可以移动点位位置；鼠标移动到连线上，按住鼠标左键并拖动，可以调节连线的弧度；</span
      >
    </p>
    <!-- 右键菜单 -->
    <div
      v-if="contextMenu.show"
      class="context-menu"
      :style="{
        left: contextMenu.x + 'px',
        top: contextMenu.y + 'px',
      }"
    >
      <button @click="editPointName" class="menu-item">编辑名称</button>
      <button @click="deletePoint" class="menu-item">删除点位</button>
    </div>

    <!-- 编辑名称弹窗 -->
    <div
      v-if="editNameModal.show"
      class="edit-name-modal"
      :style="{
        left: editNameModal.x + 'px',
        top: editNameModal.y + 'px',
      }"
    >
      <input v-model="editNameModal.name" type="text" class="name-input" />
      <div class="modal-buttons">
        <button @click="savePointName" class="save-name-btn">保存</button>
        <button @click="cancelEditName" class="cancel-name-btn">取消</button>
      </div>
    </div>
  </div>

  <!-- 全局点击监听器，用于关闭右键菜单和编辑名称弹窗 -->
  <div
    v-if="contextMenu.show || editNameModal.show"
    class="menu-overlay"
    @mousedown="handleOverlayClick"
  ></div>
</template>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
}

h1 {
  color: #333;
  margin-bottom: 20px;
}

.add-btn {
  background-color: #4caf50;
  color: white;
  border: none;
  padding: 12px 24px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.add-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.add-btn:hover {
  background-color: #45a049;
}

.save-btn {
  background-color: #2196f3;
  color: white;
  border: none;
  padding: 12px 24px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.save-btn:hover {
  background-color: #0b7dda;
}

.edit-btn {
  background-color: #ff9800;
  color: white;
  border: none;
  padding: 12px 24px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.edit-btn:hover {
  background-color: #e68a00;
}

.draw-btn {
  background-color: #9c27b0;
  color: white;
  border: none;
  padding: 12px 24px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.draw-btn:hover {
  background-color: #7b1fa2;
}

.stop-draw-btn {
  background-color: #2196f3;
  color: white;
  border: none;
  padding: 12px 24px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.stop-draw-btn:hover {
  background-color: #1976d2;
}

/* 撤销按钮样式 */
.undo-btn {
  background-color: #9e9e9e;
  color: white;
  border: none;
  padding: 12px 24px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.undo-btn:hover {
  background-color: #757575;
}

/* 保存图层按钮样式 */
.save-layer-btn {
  background-color: #8bc34a;
  color: white;
  border: none;
  padding: 12px 24px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.save-layer-btn:hover:not(:disabled) {
  background-color: #7cb342;
}

.save-layer-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 清空点位按钮样式 */
.clear-btn {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 12px 24px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.clear-btn:hover {
  background-color: #d32f2f;
}

/* 点位渲染按钮样式 */
.render-points-btn {
  background-color: #4caf50;
  color: white;
  border: none;
  padding: 12px 24px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.render-points-btn:hover {
  background-color: #45a049;
}

/* 左侧竖向工具栏样式 */
.toolbar {
  width: 40px;
  background-color: #f0f0f0;
  border-radius: 8px;
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
  margin-right: 10px;
  transition: opacity 0.3s ease;
}

/* 工具栏禁用状态 */
.toolbar.toolbar-disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.toolbar.toolbar-disabled .draggable-point {
  cursor: not-allowed;
}

/* 工具栏标题样式 */
.toolbar-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 2px solid #ddd;
}

.main-content {
  display: flex;
  align-items: center;
}

/* 可拖拽点位样式 */
.draggable-point {
  width: 25px;
  height: 25px;
  border-radius: 8px;
  cursor: grab;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  border: 3px solid white;
  transition: all 0.3s ease;
  align-self: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.draggable-point:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.draggable-point:active {
  cursor: grabbing;
  transform: scale(0.95);
}

/* 渲染控制区域样式 */
.render-control {
  display: flex;
  gap: 10px;
  align-items: center;
}

.render-input {
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 300px;
}

.canvas {
  border: 2px solid #333;
  background-color: #f5f5f5;
}

.canvas[data-editing="true"][data-saved="false"] {
  cursor: crosshair;
}

.canvas[data-editing="false"] {
  cursor: default;
}

/* 已保存状态下的光标 */
.canvas[data-editing="true"][data-saved="true"] {
  cursor: default;
}

/* 绘画模式下的特殊光标 - 圆形画笔图标 */
.canvas[data-editing="true"][data-drawing="true"] {
  cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none'%3E%3Ccircle cx='12' cy='12' r='8' fill='%2345B7D1' stroke='%230D47A1' stroke-width='2'/%3E%3C/svg%3E")
      12 12,
    auto;
}

.info {
  margin-top: 15px;
  color: #666;
}

/* 右键菜单样式 */
.context-menu {
  position: fixed;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  z-index: 1000;
  padding: 5px 0;
  min-width: 120px;
}

.menu-item {
  display: block;
  width: 100%;
  padding: 8px 16px;
  text-align: left;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}

.menu-item:hover {
  background-color: #f5f5f5;
}

/* 右键菜单遮罩层样式 */
.menu-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: transparent;
  z-index: 999; /* 位于右键菜单下方 */
}

/* 编辑名称弹窗样式 */
.edit-name-modal {
  position: fixed;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  z-index: 1001;
  padding: 10px;
  min-width: 200px;
}

.name-input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  margin-bottom: 10px;
  box-sizing: border-box;
}

.modal-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.save-name-btn {
  background-color: #2196f3;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.save-name-btn:hover {
  background-color: #0b7dda;
}

.cancel-name-btn {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.cancel-name-btn:hover {
  background-color: #d32f2f;
}

#myCanvas {
  background-image: url("./assets/mpbg.jpg");
  background-position: center;
  background-size: 150% 150%;
  background-repeat: no-repeat;
}
</style>





